﻿#include "ButtonDelegate.h"

ButtonDelegate::ButtonDelegate(QObject* parent)
	:QStyledItemDelegate(parent)
{

}

QAbstractButton* ButtonDelegate::addButton(QAbstractButton* button)
{
	m_buttons.emplace_back(button);
	return button;
}
QAbstractButton* ButtonDelegate::button(int id)
{
	Q_ASSERT(id >= 0 && id < m_buttons.size());
	return m_buttons.at(id).get();
}

int ButtonDelegate::buttontotalwidth(size_t total)const
{
	size_t count = total;
	if (-1 == count)
	{
		count = m_buttons.size();
	}

	size_t totalwidth = 0;
	for (int i = 0; i < count; i++)
	{
		totalwidth += m_buttons.at(i)->width();
	}

	return totalwidth;
}

void ButtonDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
	painter->save();


	//计算所有按钮的总宽度：
	int totalwidth = buttontotalwidth();
	//文本+按钮整体居中计算：
	int h_space = (option.rect.width() - totalwidth - m_spacing * (m_buttons.size() - 1)) / 2;
	int v_space = (option.rect.height() - m_buttons.at(0)->height()) / 2;

	//绘制按钮：
	for (int i = 0; i < m_buttons.size(); i++)
	{
		QStyleOptionButton button;					//按钮的样式选项
		button.rect = QRect(option.rect.x() + h_space + i * m_spacing + buttontotalwidth(i), option.rect.y() + v_space,
							m_buttons.at(i)->width(), m_buttons.at(i)->height());
		//启用按钮：
		button.state |= QStyle::State_Enabled;

		//鼠标移动到按钮上，让按钮的状态也设置为鼠标移动到该区域中：
		if (option.state & QStyle::State_MouseOver && button.rect.contains(m_mousePos))
		{
			button.state |= QStyle::State_MouseOver;
		}

		auto abstractbtn = m_buttons.at(i).get();
		button.text = abstractbtn->text();
		abstractbtn->style()->drawControl(QStyle::CE_PushButton, &button, painter, abstractbtn);
	}


	painter->restore();
}

bool ButtonDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index)
{
	auto ev = dynamic_cast<QMouseEvent*>(event);

	if (event->type() == QEvent::MouseMove)						//鼠标移动，获取坐标
	{
		m_mousePos = ev->position().toPoint();

		//更新数据：
		auto view = dynamic_cast<QAbstractItemView*>(parent());
		if (view)
		{
			view->viewport()->update(option.rect);
		}
	}
	else if (event->type() == QEvent::MouseButtonRelease)		//鼠标按下
	{
		int totalwidth = buttontotalwidth();
		int h_space = (option.rect.width() - totalwidth - m_spacing * (m_buttons.size() - 1)) / 2;
		int v_space = (option.rect.height() - m_buttons.at(0)->height()) / 2;


		for (int i = 0; i < m_buttons.size(); i++)
		{
			QRect rect(option.rect.x() + h_space + i * m_spacing + buttontotalwidth(i), option.rect.y() + v_space,
				m_buttons.at(i)->width(), m_buttons.at(i)->height());


			if (rect.contains(ev->position().toPoint()))
			{
				emit buttonCilcked(i, index);
				break;
			}
		}
	}

	return QStyledItemDelegate::editorEvent(event,model,option,index);
}
